<template>
  <div class="config-editor-layout">
    <!-- 头部工具栏 -->
    <div class="config-editor-header">
      <div class="header-left">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/configs' }">配置中心</el-breadcrumb-item>
          <el-breadcrumb-item>配置导入导出</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-right">
        <el-space>
          <el-button @click="refreshSchemas" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-space>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="config-editor-main">
      <div class="import-export-content">
        <el-row :gutter="24">
          <!-- 导入配置 -->
          <el-col :span="12">
            <el-card class="import-card">
              <template #header>
                <div class="card-header">
                  <el-icon size="20"><Upload /></el-icon>
                  <span>配置导入</span>
                </div>
              </template>

              <div class="import-section">
                <el-form :model="importForm" label-width="100px">
                  <el-form-item label="配置类型">
                    <el-select 
                      v-model="importForm.type" 
                      placeholder="选择要导入的配置类型"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="schema in availableSchemas"
                        :key="schema.type"
                        :label="schema.name"
                        :value="schema.type"
                      >
                        <div class="schema-option">
                          <span>{{ schema.name }}</span>
                          <span class="schema-desc">{{ schema.description }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item label="导入格式">
                    <el-radio-group v-model="importForm.format">
                      <el-radio label="json">JSON</el-radio>
                      <el-radio label="xlsx">Excel</el-radio>
                      <el-radio label="yaml">YAML</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="导入选项">
                    <div class="import-options">
                      <el-checkbox v-model="importForm.options.merge">
                        合并模式（更新已存在的配置）
                      </el-checkbox>
                      <el-checkbox v-model="importForm.options.validate">
                        导入前验证数据
                      </el-checkbox>
                      <el-checkbox v-model="importForm.options.backup">
                        导入前创建备份
                      </el-checkbox>
                    </div>
                  </el-form-item>

                  <el-form-item label="选择文件">
                    <el-upload
                      ref="uploadRef"
                      :before-upload="handleBeforeUpload"
                      :on-change="handleFileChange"
                      :auto-upload="false"
                      :show-file-list="true"
                      :limit="1"
                      :accept="getAcceptTypes()"
                      drag
                    >
                      <el-icon size="60"><UploadFilled /></el-icon>
                      <div class="upload-text">
                        <p>将文件拖拽到此处，或<em>点击上传</em></p>
                        <p class="upload-tip">支持 {{ getSupportedFormats() }} 格式</p>
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-form>

                <div class="import-actions">
                  <el-button 
                    type="primary" 
                    @click="handleImport"
                    :loading="importing"
                    :disabled="!selectedFile || !importForm.type"
                  >
                    <el-icon><Upload /></el-icon>
                    开始导入
                  </el-button>
                  <el-button @click="handlePreviewImport" :disabled="!selectedFile">
                    <el-icon><View /></el-icon>
                    预览数据
                  </el-button>
                </div>

                <!-- 导入结果 -->
                <div v-if="importResult" class="import-result">
                  <el-alert
                    :type="importResult.success ? 'success' : 'error'"
                    :title="importResult.title"
                    :description="importResult.description"
                    show-icon
                    :closable="false"
                  />
                  
                  <div v-if="importResult.details" class="result-details">
                    <el-descriptions :column="2" size="small">
                      <el-descriptions-item label="导入成功">
                        {{ importResult.details.imported }} 项
                      </el-descriptions-item>
                      <el-descriptions-item label="跳过">
                        {{ importResult.details.skipped }} 项
                      </el-descriptions-item>
                      <el-descriptions-item label="错误" :span="2" v-if="importResult.details.errors.length > 0">
                        <div class="error-list">
                          <el-tag type="danger" v-for="error in importResult.details.errors" :key="error">
                            {{ error }}
                          </el-tag>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 导出配置 -->
          <el-col :span="12">
            <el-card class="export-card">
              <template #header>
                <div class="card-header">
                  <el-icon size="20"><Download /></el-icon>
                  <span>配置导出</span>
                </div>
              </template>

              <div class="export-section">
                <el-form :model="exportForm" label-width="100px">
                  <el-form-item label="配置类型">
                    <el-checkbox-group v-model="exportForm.types">
                      <div class="export-types">
                        <el-checkbox
                          v-for="schema in availableSchemas"
                          :key="schema.type"
                          :label="schema.type"
                          border
                        >
                          <div class="export-type-item">
                            <span class="type-name">{{ schema.name }}</span>
                            <span class="type-count">({{ getConfigCount(schema.type) }} 项)</span>
                          </div>
                        </el-checkbox>
                      </div>
                    </el-checkbox-group>
                  </el-form-item>

                  <el-form-item label="导出格式">
                    <el-radio-group v-model="exportForm.format">
                      <el-radio label="json">JSON</el-radio>
                      <el-radio label="xlsx">Excel</el-radio>
                      <el-radio label="yaml">YAML</el-radio>
                      <el-radio label="typescript">TypeScript</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="导出选项">
                    <div class="export-options">
                      <el-checkbox 
                        v-model="exportForm.options.minify"
                        :disabled="exportForm.format !== 'json'"
                      >
                        压缩格式（仅JSON）
                      </el-checkbox>
                      <el-checkbox 
                        v-model="exportForm.options.includeComments"
                        :disabled="!['yaml', 'typescript'].includes(exportForm.format)"
                      >
                        包含注释（YAML/TS）
                      </el-checkbox>
                    </div>
                  </el-form-item>
                </el-form>

                <div class="export-actions">
                  <el-button 
                    type="primary" 
                    @click="handleExport"
                    :loading="exporting"
                    :disabled="exportForm.types.length === 0"
                  >
                    <el-icon><Download /></el-icon>
                    导出配置
                  </el-button>
                  <el-button @click="exportForm.types = getAllTypes()">
                    全选
                  </el-button>
                  <el-button @click="exportForm.types = []">
                    清除
                  </el-button>
                </div>

                <!-- 导出历史 -->
                <div v-if="exportHistory.length > 0" class="export-history">
                  <h4>最近导出</h4>
                  <div class="history-list">
                    <div 
                      v-for="item in exportHistory" 
                      :key="item.filename"
                      class="history-item"
                    >
                      <div class="history-info">
                        <span class="filename">{{ item.filename }}</span>
                        <span class="filesize">{{ formatFileSize(item.fileSize) }}</span>
                      </div>
                      <el-button 
                        size="small" 
                        type="primary" 
                        link
                        @click="downloadFile(item.downloadUrl, item.filename)"
                      >
                        下载
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 数据预览对话框 -->
        <el-dialog 
          v-model="showPreviewDialog" 
          title="数据预览" 
          width="80%"
          :close-on-click-modal="false"
        >
          <div class="preview-content">
            <div class="preview-header">
              <el-space>
                <el-tag>配置类型: {{ importForm.type }}</el-tag>
                <el-tag>数据格式: {{ importForm.format.toUpperCase() }}</el-tag>
                <el-tag>记录数量: {{ previewData.length }}</el-tag>
              </el-space>
            </div>

            <el-table
              :data="previewData"
              max-height="400"
              border
              style="width: 100%"
            >
              <el-table-column
                v-for="column in previewColumns"
                :key="column.prop"
                :prop="column.prop"
                :label="column.label"
                :width="column.width"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  <span v-if="typeof row[column.prop] === 'object'">
                    {{ JSON.stringify(row[column.prop]) }}
                  </span>
                  <span v-else>{{ row[column.prop] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <template #footer>
            <el-button @click="showPreviewDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmImport">
              确认导入
            </el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { configApi } from '@/api/config'
import type { ConfigSchemaInfo } from '@/types/config'
import { 
  Refresh, Upload, Download, View, UploadFilled 
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const importing = ref(false)
const exporting = ref(false)
const availableSchemas = ref<ConfigSchemaInfo[]>([])
const selectedFile = ref<File | null>(null)
const uploadRef = ref()
const showPreviewDialog = ref(false)
const previewData = ref<any[]>([])
const previewColumns = ref<any[]>([])

// 表单数据
const importForm = ref({
  type: '',
  format: 'json',
  options: {
    merge: false,
    validate: true,
    backup: true
  }
})

const exportForm = ref({
  types: [] as string[],
  format: 'json',
  options: {
    minify: false,
    includeComments: true
  }
})

// 结果数据
const importResult = ref<any>(null)
const exportHistory = ref<any[]>([])

// 计算属性
const getAcceptTypes = () => {
  switch (importForm.value.format) {
    case 'json': return '.json'
    case 'xlsx': return '.xlsx,.xls'
    case 'yaml': return '.yaml,.yml'
    default: return '*'
  }
}

const getSupportedFormats = () => {
  const formats = {
    json: 'JSON',
    xlsx: 'Excel',
    yaml: 'YAML'
  }
  return Object.values(formats).join(', ')
}

const getAllTypes = () => {
  return availableSchemas.value.map(schema => schema.type)
}

const getConfigCount = (type: string) => {
  // 这里应该从API获取实际的配置数量
  // 暂时返回模拟数据
  const counts: Record<string, number> = {
    equipment: 25,
    skill: 40,
    prop: 15
  }
  return counts[type] || 0
}

// 方法
const refreshSchemas = async () => {
  loading.value = true
  try {
    const response = await configApi.getConfigSchemas()
    if (response.success && response.data) {
      availableSchemas.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取配置Schema失败')
  } finally {
    loading.value = false
  }
}

const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
  importResult.value = null
}

const handleBeforeUpload = () => {
  return false // 阻止自动上传
}

const handlePreviewImport = async () => {
  if (!selectedFile.value) return

  try {
    const fileContent = await readFileContent(selectedFile.value)
    const parsedData = parseFileContent(fileContent, importForm.value.format)
    
    if (Array.isArray(parsedData) && parsedData.length > 0) {
      previewData.value = parsedData.slice(0, 10) // 只预览前10条
      
      // 生成列配置
      const firstItem = parsedData[0]
      previewColumns.value = Object.keys(firstItem).map(key => ({
        prop: key,
        label: key,
        width: 150
      }))
      
      showPreviewDialog.value = true
    } else {
      ElMessage.error('文件内容格式不正确')
    }
  } catch (error) {
    ElMessage.error('文件解析失败: ' + (error as any).message)
  }
}

const handleImport = async () => {
  if (!selectedFile.value || !importForm.value.type) return

  importing.value = true
  importResult.value = null

  try {
    const fileContent = await readFileContent(selectedFile.value)
    const parsedData = parseFileContent(fileContent, importForm.value.format)
    
    const response = await configApi.importConfigs(parsedData, {
      type: importForm.value.type,
      ...importForm.value.options
    })
    
    if (response.success) {
      importResult.value = {
        success: true,
        title: '导入成功',
        description: `成功导入 ${response.data?.imported || 0} 项配置`,
        details: response.data
      }
      
      // 清除文件选择
      selectedFile.value = null
      uploadRef.value?.clearFiles()
      
    } else {
      importResult.value = {
        success: false,
        title: '导入失败',
        description: response.message || '导入过程中发生错误'
      }
    }
  } catch (error) {
    importResult.value = {
      success: false,
      title: '导入失败',
      description: (error as any).message
    }
  } finally {
    importing.value = false
  }
}

const confirmImport = () => {
  showPreviewDialog.value = false
  handleImport()
}

const handleExport = async () => {
  if (exportForm.value.types.length === 0) return

  exporting.value = true
  try {
    const response = await configApi.exportConfigs({
      types: exportForm.value.types,
      ...exportForm.value.options
    })
    
    if (response.success && response.data) {
      // 添加到导出历史
      exportHistory.value.unshift({
        filename: response.data.filename,
        downloadUrl: response.data.downloadUrl,
        fileSize: response.data.fileSize,
        timestamp: Date.now()
      })
      
      // 只保留最近5次导出记录
      if (exportHistory.value.length > 5) {
        exportHistory.value = exportHistory.value.slice(0, 5)
      }
      
      // 自动下载
      downloadFile(response.data.downloadUrl, response.data.filename)
      
      ElMessage.success('配置导出成功')
    } else {
      ElMessage.error('配置导出失败')
    }
  } catch (error) {
    ElMessage.error('配置导出失败: ' + (error as any).message)
  } finally {
    exporting.value = false
  }
}

const readFileContent = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => resolve(e.target?.result as string)
    reader.onerror = reject
    reader.readAsText(file)
  })
}

const parseFileContent = (content: string, format: string) => {
  switch (format) {
    case 'json':
      return JSON.parse(content)
    case 'yaml':
      // 简单的YAML解析（生产环境应使用专业的YAML库）
      throw new Error('YAML格式解析需要额外的库支持')
    case 'xlsx':
      throw new Error('Excel格式解析需要额外的库支持')
    default:
      throw new Error(`不支持的文件格式: ${format}`)
  }
}

const downloadFile = (url: string, filename: string) => {
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 生命周期
onMounted(() => {
  refreshSchemas()
})
</script>

<style scoped>
.import-export-content {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.import-section, .export-section {
  padding: 0;
}

.import-options, .export-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.schema-option {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.schema-desc {
  font-size: 12px;
  color: var(--config-editor-text-secondary);
}

.upload-text {
  text-align: center;
  color: var(--config-editor-text-secondary);
}

.upload-text em {
  color: var(--config-editor-primary);
  font-style: normal;
}

.upload-tip {
  font-size: 12px;
  margin-top: 4px;
}

.import-actions, .export-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.import-result {
  margin-top: 20px;
}

.result-details {
  margin-top: 16px;
}

.error-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.export-types {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.export-type-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.type-name {
  font-weight: 500;
}

.type-count {
  font-size: 12px;
  color: var(--config-editor-text-secondary);
}

.export-history {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--config-editor-border);
}

.export-history h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--config-editor-text);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: var(--config-editor-bg);
  border-radius: 4px;
}

.history-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.filename {
  font-size: 13px;
  color: var(--config-editor-text);
}

.filesize {
  font-size: 11px;
  color: var(--config-editor-text-secondary);
}

.preview-content {
  max-height: 500px;
}

.preview-header {
  margin-bottom: 16px;
}
</style>
